package com.dly.hope.servce.impl;

import com.dly.hope.constant.ExceptionConstant;
import com.dly.hope.constant.GlobalException;
import com.dly.hope.dto.EmailFileDto;
import com.dly.hope.dto.EmailSendDto;
import com.dly.hope.servce.EmailService;
import com.dly.hope.utils.ExceptionPropertiesUtil;
import com.dly.hope.utils.FileUtil;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import io.vavr.control.Try;
import jodd.util.StringPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;

/**
 * @author linyu.dai
 * @project myserve
 * @description 发送邮件
 * @creat 2022/8/28 11:29:17
 */
@Service
@Slf4j
public class EmailServiceImpl implements EmailService {

    @Resource
    private JavaMailSender javaMailSender;

    @Value("${email.from:learnerdly@163.com}")
    private String from;

    /**
     * 发件人名字
     */
    @Value("${email.from:浮生若梦}")
    private String personal;

    @Resource
    private ExecutorService executorService;

    @Override
    public void sendEmail(EmailSendDto emailSendDto) {
        CompletableFuture.runAsync(() -> Try.run(() -> {
                    StopWatch stopWatch = new StopWatch("发送邮件");
                    stopWatch.start("开始发送邮件");

                    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
                    MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, StandardCharsets.UTF_8.name());
                    messageHelper.setFrom(from, personal);

                    //设置主题
                    messageHelper.setSubject(emailSendDto.getSubject());

                    //设置正文内容
                    messageHelper.setText(emailSendDto.getMailText(), emailSendDto.isHtml());

                    //遍历接收人
                    for (String to : emailSendDto.getEmailToList()) {
                        messageHelper.addTo(to);
                    }

                    if (CollectionUtils.isNotEmpty(emailSendDto.getCcList())) {
                        //遍历抄送人
                        for (String cc : emailSendDto.getCcList()) {
                            messageHelper.addCc(cc);
                        }
                    }

                    if (CollectionUtils.isNotEmpty(emailSendDto.getFileList())) {
                        //遍历附件
                        for (EmailFileDto dto : emailSendDto.getFileList()) {
                            messageHelper.addAttachment(StringUtils.join(StringUtils.isNotEmpty(dto.getName()) ? dto.getName() : UUID.randomUUID(), StringPool.DOT, dto.getSuffix()), dto.getFile());
                        }
                    }

                    javaMailSender.send(mimeMessage);
                    stopWatch.stop();

                    //打印日志
                    log.info("当前线程：" + Thread.currentThread().getName());
                    log.info(stopWatch.prettyPrint());
                }).onFailure(e -> log.error(e.getClass().getSimpleName(), e))
                //删除文件
                .andFinally(() -> close(emailSendDto.getFileList()))
                .getOrNull(), executorService);
    }

    private void close(List<EmailFileDto> fileList){
        if(CollectionUtils.isNotEmpty(fileList)){
            fileList.forEach(f-> FileUtil.delete(f.getFile()));
        }
    }

}
